package com.linksfield.topup.utils;

import org.apache.http.HttpEntity;
import org.apache.http.HttpStatus;
import org.apache.http.StatusLine;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

public class HttpUtil {

    public static String httpPost(String url, String param) {
//        RequestConfig requestConfig = RequestConfig.custom()
//                .setConnectTimeout(30000)
//                .setConnectionRequestTimeout(20000)
//                .setSocketTimeout(30000)
//                .build();
        RequestConfig requestConfig = RequestConfig.custom()
                .setConnectTimeout(50000)
                .setConnectionRequestTimeout(50000)
                .setSocketTimeout(50000)
                .build();
        CloseableHttpClient httpClient = HttpClients.custom().setDefaultRequestConfig(requestConfig).build();
        HttpPost httpPost = new HttpPost(url);
        httpPost.setHeader("Accept", "application/json");
        httpPost.setHeader("Content-Type", "application/json");
        httpPost.setHeader("x-access-token", "xAccessToken");
        StringEntity entity = null;
        if (param != null) {
            entity = new StringEntity(param, "UTF-8");
        }
        httpPost.setEntity(entity);
        CloseableHttpResponse response = null;
        String returnStr = "";
        try {
            response = httpClient.execute(httpPost);
            StatusLine status = response.getStatusLine();
            if (status.getStatusCode() == HttpStatus.SC_OK) {
                HttpEntity httpEntity = response.getEntity();
                returnStr = EntityUtils.toString(httpEntity, "UTF-8");
            } else {
                returnStr = "Http请求出现异常！";
                return returnStr;
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            responseClose(response);
        }
        return returnStr;
    }

    /**
     * 资源释放
     */
    private static void responseClose(CloseableHttpResponse response) {
        try {
            if (response != null) {
                response.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


}
